package cn.zzq.aix.builder.utils;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.parser.Parser;
import org.jsoup.parser.XmlTreeBuilder;

public class TextQuoter {
	Document doc = null;

	public TextQuoter(Path xmlFile) {
		this(xmlFile.readAsText());
	}

	public TextQuoter(String xml) {
		doc = Jsoup.parse(xml, "", new Parser(new XmlTreeBuilder()));

	}

	public String replace(String origin) {
		Element ele = doc.getAllElements().get(0);

		origin = origin.trim();// 清空首尾的空格
		for (String id : getSubUtil(origin)) {
			Element in = ele.getElementById(id);
			String idwrap = "${" + id + "}$";
			origin = origin.replace(idwrap, in == null ? idwrap : in.html());
		}
		return origin.replace("/$", "$")//
				.replace("/{", "{")//
				.replace("/}", "}");
	}

	public static List<String> getSubUtil(String str) {
		List<String> list = new ArrayList<String>();
		// 正则表达式匹配${这里的字符串}$
		Pattern pattern = Pattern.compile("[$][{](.*?)[}][$]");// 匹配的模式
		Matcher m = pattern.matcher(str);
		while (m.find()) {
			int i = 1;
			list.add(m.group(i));
			i++;
		}
		return list;
	}

	public static void main(String[] args) {
		TextQuoter tq = new TextQuoter(new Path("Test.xml"));
		System.out.println(tq.replace("/$/{ta}$ ${test12}$ ${test1}$"));
	}
}
